Automatic generation of smart contracts

ABSTRACT

An example operation may include one or more of defining a target specification for a blockchain smart contract, obtaining a plurality of reusable smart contracts, and creating the blockchain smart contract. Creating the blockchain smart contract includes combining the plurality of reusable smart contracts and the target specification into a first set of contracts, transforming the first set of contracts into a second set of contracts, selecting a target contract from the second set of contracts, and translating the target contract into an executable form of the blockchain smart contract. The target specification includes a regular event pattern and a temporal constraint the blockchain smart contract must satisfy. Each of the reusable smart contracts includes a reusable event pattern.

TECHNICAL FIELD

This application generally relates to a database storage system, andmore particularly, to automatic generation of smart contracts inblockchain networks.

BACKGROUND

A centralized database stores and maintains data in one single database(e.g., database server) at one location. This location is often acentral computer, for example, a desktop central processing unit (CPU),a server CPU, or a mainframe computer. Information stored on acentralized database is typically accessible from multiple differentpoints. Multiple users or client workstations can work simultaneously onthe centralized database, for example, based on a client/serverconfiguration. A centralized database is easy to manage, maintain, andcontrol, especially for purposes of security because of its singlelocation. Within a centralized database, data redundancy is minimized asa single storing place of all data also implies that a given set of dataonly has one primary record.

However, a centralized database suffers from significant drawbacks. Forexample, a centralized database has a single point of failure. Inparticular, if there are no fault-tolerance considerations and ahardware failure occurs (for example a hardware, firmware, and/or asoftware failure), all data within the database is lost and work of allusers is interrupted. In addition, centralized databases are highlydependent on network connectivity. As a result, the slower theconnection, the amount of time needed for each database access isincreased. Another drawback is the occurrence of bottlenecks when acentralized database experiences high traffic due to a single location.Furthermore, a centralized database provides limited access to databecause only one copy of the data is maintained by the database. As aresult, multiple devices cannot access the same piece of data at thesame time without creating significant problems or risk overwritingstored data. Furthermore, because a database storage system has minimalto no data redundancy, data that is unexpectedly lost is very difficultto retrieve other than through manual operation from back-up storage.

Conventionally, a centralized database is limited by a lack of supportfor smart contracts, and therefore an inability to create new executablesmart contracts from a protocol, properties, and rules. As such, what isneeded is a solution to overcome these significant drawbacks.

SUMMARY

One example embodiment provides a system that includes a blockchainnetwork and a computing system. The blockchain network includes one ormore blockchain nodes, which includes a blockchain smart contract. Thecomputing system is configured to define a target specification for theblockchain smart contract, obtain a plurality of reusable smartcontracts, combine the plurality of reusable smart contracts and targetspecification into a first set of contracts, enforce the targetspecification on the first set of contracts, transform the first set ofcontracts into a second set of contracts, select a target contract fromthe second set of contracts, and translate the target contract into anexecutable form of the blockchain smart contract. The targetspecification includes a regular event pattern and a temporal constraintthe blockchain smart contract must satisfy. Each reusable smart contractincludes a reusable event pattern.

Another example embodiment provides a method that includes one or moreof defining a target specification for a blockchain smart contract,obtaining a plurality of reusable smart contracts, and creating theblockchain smart contract. Creating the blockchain smart contractincludes combining the plurality of reusable smart contracts and thetarget specification into a first set of contracts, transforming thefirst set of contracts into a second set of contracts, selecting atarget contract from the second set of contracts, and translating thetarget contract into an executable form of the blockchain smartcontract. The target specification includes a regular event pattern anda temporal constraint the blockchain smart contract must satisfy. Eachof the reusable smart contracts includes a reusable event pattern.

A further example embodiment provides a non-transitory computer readablemedium comprising instructions, that when read by a processor, cause theprocessor to perform one or more of defining a target specification fora blockchain smart contract, obtaining a plurality of reusable smartcontracts, and creating the blockchain smart contract. Creating theblockchain smart contract includes combining the plurality of reusablesmart contracts and the target specification into a first set ofcontracts, transforming the first set of contracts into a second set ofcontracts, selecting a target contract from the second set of contracts,and translating the target contract into an executable form of theblockchain smart contract. The target specification includes a regularevent pattern and a temporal constraint the blockchain smart contractmust satisfy. Each of the reusable smart contracts includes a reusableevent pattern.

Another example embodiment provides another method that includes one ormore of defining a target specification for a blockchain smart contract,obtaining a plurality of reusable smart contracts, and creating theblockchain smart contract. Creating the blockchain smart contractincludes combining the plurality of reusable smart contracts and thetarget specification into a first set of contracts, transforming thefirst set of contracts into a second set of contracts, selecting atarget contract from the second set of contracts; and translating thetarget contract into an executable form of the blockchain smartcontract. The target specification includes a protocol and one or moreproperties each including a temporal constraint the blockchain smartcontract must satisfy. Each of the plurality of reusable smart contractsincludes a reusable protocol.

A further example embodiment provides another non-transitory computerreadable medium comprising instructions, that when read by a processor,cause the processor to perform one or more of defining a targetspecification for a blockchain smart contract, obtaining a plurality ofreusable smart contracts, and creating the blockchain smart contract.Creating the blockchain smart contract includes combining the pluralityof reusable smart contracts and the target specification into a firstset of contracts, transforming the first set of contracts into a secondset of contracts, selecting a target contract from the second set ofcontracts; and translating the target contract into an executable formof the blockchain smart contract. The target specification includes aprotocol and one or more properties each including a temporal constraintthe blockchain smart contract must satisfy. Each of the plurality ofreusable smart contracts includes a reusable protocol.

BRIEF DESCRIPTION OF THE DRAWINGS

FIG. 1A illustrates a network diagram of a blockchain system including adatabase and smart contracts, according to example embodiments.

FIG. 1B illustrates a diagram of components operating with smartcontracts and a database, according to example embodiments.

FIG. 1C illustrates a diagram of components operating with smartcontracts and a database, according to example embodiments.

FIG. 1D illustrates a diagram of components operating with smartcontracts and a database, according to example embodiments.

FIG. 2 illustrates an example of a transactional flow between nodes of ablockchain, according to example embodiments.

FIG. 3 illustrates a permissioned network, according to exampleembodiments.

FIG. 4 illustrates a flow diagram of an example method of enforcing asmart contract execution hierarchy in a blockchain, according to exampleembodiments.

FIG. 5A illustrates a flow diagram of an example method of executablesmart contract generation in a blockchain, according to exampleembodiments.

FIG. 5B illustrates a flow diagram of an example method of utilizingcontract composition operators in a blockchain, according to exampleembodiments.

FIG. 5C illustrates a flow diagram of an example method of automaticsmart contract generation in a blockchain, according to exampleembodiments.

FIG. 6A illustrates an example system configured to perform one or moreoperations described herein, according to example embodiments.

FIG. 6B illustrates a further example system configured to perform oneor more operations described herein, according to example embodiments.

FIG. 6C illustrates a smart contract configuration among contractingparties and a mediating server configured to enforce the smart contractterms on the blockchain according to example embodiments.

FIG. 6D illustrates an additional example system, according to exampleembodiments.

FIG. 7A illustrates a process of new data being added to a database,according to example embodiments.

FIG. 7B illustrates contents a data block including the new data,according to example embodiments.

FIG. 8 illustrates an example system that supports one or more of theexample embodiments.

DETAILED DESCRIPTION

It will be readily understood that the instant components, as generallydescribed and illustrated in the figures herein, may be arranged anddesigned in a wide variety of different configurations. Thus, thefollowing detailed description of the embodiments of at least one of amethod, apparatus, non-transitory computer readable medium and system,as represented in the attached figures, is not intended to limit thescope of the application as claimed but is merely representative ofselected embodiments.

The instant features, structures, or characteristics as describedthroughout this specification may be combined in any suitable manner inone or more embodiments. For example, the usage of the phrases “exampleembodiments”, “some embodiments”, or other similar language, throughoutthis specification refers to the fact that a particular feature,structure, or characteristic described in connection with the embodimentmay be included in at least one embodiment. Thus, appearances of thephrases “example embodiments”, “in some embodiments”, “in otherembodiments”, or other similar language, throughout this specificationdo not necessarily all refer to the same group of embodiments, and thedescribed features, structures, or characteristics may be combined inany suitable manner in one or more embodiments.

In addition, while the term “message” may have been used in thedescription of embodiments, the application may be applied to many typesof network data, such as, packet, frame, datagram, etc. The term“message” also includes packet, frame, datagram, and any equivalentsthereof. Furthermore, while certain types of messages and signaling maybe depicted in exemplary embodiments they are not limited to a certaintype of message, and the application is not limited to a certain type ofsignaling.

Example embodiments provide methods, systems, components, non-transitorycomputer readable media, devices, and/or networks, which provide inputmapping used in the formation of Linear Dynamic Logic used to createblockchain smart contracts.

A decentralized database is a distributed storage system which includesmultiple nodes that communicate with each other. A blockchain is anexample of a decentralized database which includes an append-onlyimmutable data structure resembling a distributed ledger capable ofmaintaining records between mutually untrusted parties. The untrustedparties are referred to herein as peers or peer nodes. Each peermaintains a copy of the database records and no single peer can modifythe database records without a consensus being reached among thedistributed peers. For example, the peers may execute a consensusprotocol to validate blockchain storage transactions, group the storagetransactions into blocks, and build a hash chain over the blocks. Thisprocess forms the ledger by ordering the storage transactions, as isnecessary, for consistency. In a public or permission-less blockchain,anyone can participate without a specific identity. Public blockchainsoften involve native cryptocurrency and use consensus based on variousprotocols such as Proof of Work (PoW). On the other hand, a permissionedblockchain database provides a system which can secure inter-actionsamong a group of entities which share a common goal but which do notfully trust one another, such as businesses that exchange funds, goods,information, and the like.

A blockchain operates arbitrary, programmable logic, tailored to adecentralized storage scheme and referred to as “smart contracts” or“chaincodes.” In some cases, specialized chaincodes may exist formanagement functions and parameters which are referred to as systemchaincode. Smart contracts are trusted distributed applications whichleverage tamper-proof properties of the blockchain database and anunderlying agreement between nodes which is referred to as anendorsement or endorsement policy. In general, blockchain transactionstypically must be “endorsed” before being committed to the blockchainwhile transactions which are not endorsed are disregarded. A typicalendorsement policy allows chaincode to specify endorsers for atransaction in the form of a set of peer nodes that are necessary forendorsement. When a client sends the transaction to the peers specifiedin the endorsement policy, the transaction is executed to validate thetransaction. After validation, the transactions enter an ordering phasein which a consensus protocol is used to produce an ordered sequence ofendorsed transactions grouped into blocks.

Nodes are the communication entities of the blockchain system. A “node”may perform a logical function in the sense that multiple nodes ofdifferent types can run on the same physical server. Nodes are groupedin trust domains and are associated with logical entities that controlthem in various ways. Nodes may include different types, such as aclient or submitting-client node which submits a transaction-invocationto an endorser (e.g., peer), and broadcasts transaction-proposals to anordering service (e.g., ordering node). Another type of node is a peernode which can receive client submitted transactions, commit thetransactions and maintain a state and a copy of the ledger of blockchaintransactions. Peers can also have the role of an endorser, although itis not a requirement. An ordering-service-node or orderer is a noderunning the communication service for all nodes, and which implements adelivery guarantee, such as a broadcast to each of the peer nodes in thesystem when committing transactions and modifying a world state of theblockchain, which is another name for the initial blockchain transactionwhich normally includes control and setup information.

A ledger is a sequenced, tamper-resistant record of all statetransitions of a blockchain. State transitions may result from chaincodeinvocations (i.e., transactions) submitted by participating parties(e.g., client nodes, ordering nodes, endorser nodes, peer nodes, etc.).A transaction may result in a set of asset key-value pairs beingcommitted to the ledger as one or more operands, such as creates,updates, deletes, and the like. The ledger includes a blockchain (alsoreferred to as a chain) which is used to store an immutable, sequencedrecord in blocks. The ledger also includes a state database whichmaintains a current state of the blockchain. There is typically oneledger per channel. Each peer node maintains a copy of the ledger foreach channel of which they are a member.

A chain is a transaction log which is structured as hash-linked blocks,and each block contains a sequence of N transactions where N is equal toor greater than one. The block header includes a hash of the block'stransactions, as well as a hash of the prior block's header. In thisway, all transactions on the ledger may be sequenced andcryptographically linked together. Accordingly, it is not possible totamper with the ledger data without breaking the hash links. A hash of amost recently added blockchain block represents every transaction on thechain that has come before it, making it possible to ensure that allpeer nodes are in a consistent and trusted state. The chain may bestored on a peer node file system (i.e., local, attached storage, cloud,etc.), efficiently supporting the append-only nature of the blockchainworkload.

The current state of the immutable ledger represents the latest valuesfor all keys that are included in the chain transaction log. Because thecurrent state represents the latest key values known to a channel, it issometimes referred to as a world state. Chaincode invocations executetransactions against the current state data of the ledger. To make thesechaincode interactions efficient, the latest values of the keys may bestored in a state database. The state database may be simply an indexedview into the chain's transaction log, it can therefore be regeneratedfrom the chain at any time. The state database may automatically berecovered (or generated if needed) upon peer node startup, and beforetransactions are accepted.

Some benefits of the instant solutions described and depicted hereininclude improved smart contract formation and enforcement. Recently,despite the growing popularity of smart contracts, one serious concernis arising among both industry and academia, that is, whether they workautonomously without human intervention really as intended and, whenthat is uncertain, ensuring that contracts meet particular requirements.To resolve this, a new formal approach to smart contract development isdescribed herein: instead of defining contracts just as programs inconventional languages, they should be defined using formal logic sothat it is possible to verify whether they meet particular requirements,and enforce them if necessary. The primary challenge is that expressiveformal logic often turns out to be undecidable and consequentlyexecutable programs cannot be generated. As a solution, each contractdefinition is divided into two layers, namely a specification layer in adecidable logic called Linear Dynamic Logic on finite traces (LDL_(f))for verification and enforcement of requirements, and a rule layer fordefining implementation details, while the consistency between the twolayers is systematically guaranteed. Based on this, it also becomespossible to automatically generate executable contract programs fromtheir formal specification, which leads to improving the trustworthinessof contracts. Evaluation on Hyperledger Fabric shows the feasibility andhigh effectiveness of this approach.

Blockchain is different from a traditional database in that blockchainis not a central storage but rather a decentralized, immutable, andsecure storage, where nodes must share in changes to records in thestorage. Some properties that are inherent in blockchain and which helpimplement the blockchain include, but are not limited to, an immutableledger, smart contracts, security, privacy, decentralization, consensus,endorsement, accessibility, and the like, which are further describedherein. According to various aspects, the improved smart contractformation and enforcement is implemented due to utilizing decidablelogic called Linear Dynamic Logic on finite traces.

One of the benefits of the example embodiments is that it improves thefunctionality of a computing system by improving blockchain operationand functionality. Through the blockchain system described herein, acomputing system can perform automated smart contract generation andrequirement enforcement. New smart contracts may be assembled thoughvarious means described herein. For example, a new smart contract may beassembled from a protocol, properties, and rules, or from reusable smartcontracts and a new requirements specification. A series of compositionoperators may also aid in the formation of new smart contracts.

The example embodiments provide numerous benefits over a traditionaldatabase. For example, through the blockchain the embodiments provideimproved smart contract formation and requirement enforcement Meanwhile,a traditional database could not be used to implement the exampleembodiments because traditional databases do not support smart contractsor chaincodes. Accordingly, the example embodiments provide for aspecific solution providing improved productivity, reusability, andcorrectness for smart contracts.

The example embodiments also change how data may be stored within ablock structure of the blockchain. For example, event, transition, andstate information that derive from SCXML may be stored within datablocks of a blockchain. By storing the event, transition, and stateinformation within data blocks of a blockchain, the new data may beappended to an immutable ledger through a hash-linked chain of blocks.In some embodiments, the data block may be different than a traditionaldata block by including the event, transition, and state informationthat is used for smart contract formation of a blockchain.

While the idea is widespread, the term “smart contract” has no cleardefinition. Two different notions exist that apply to ‘smart contracts’:One is smart contract code, which is a piece of code written in aprogramming language that runs on a blockchain platform. The other issmart legal contracts. They are more than just codes, but are supposedto complement or replace existing legal contracts and to be legallyenforceable as such. Taking this into account, existing efforts relatedto smart contract development are described.

Major blockchain platforms provide tools for smart contract development,which include compilers of contract programming languages. Bitcoinsupports a Forth-like stack-based language without loops, called Script.It is Turing-incomplete and used mostly for digital signatureverification. Ethereum was originally conceived to improve Bitcoin witha full-fledged programming language for application development. Inaddition to Solidity, it supports LLL, Serpent, and Mutan. They all runon Ethereum Virtual Machine (EVM). Corda is developed mainly forfinancial applications (at least initially), and its design choice isrelatively conservative. It supports Java, and also Kotlin, another JavaVirtual Machine language officially supported in the Android operatingsystem. What differentiates Corda's smart contracts from others is thatthey can have legal proses attached to smart contract code so that onecan refer to them in case of disputes. Hyperledger Fabric supports smartcontracts written in the Go language, called chaincodes. Chaincodes aremostly similar to Ethereum smart contracts, except that they depend onDocker instead of virtual machine. From third parties other thanblockchain platform providers, several new cross-platform languages havebeen proposed.

Among those, Simplicity is a strongly-typed combinatory-based low-levellanguage that features analysis of resource usage on virtual machinesincluding its own Bit Machine. Primarily owing to itsTuring-incompleteness, temporal and spatial boundaries of resource usecan be estimated by static means. Ergo is another strongly-typedfunctional language that has a platform-independent semantics. Similarto Simplicity, it also imposes a restriction on iterations andguarantees termination of contract execution.

One important feature that contract programming languages should supportis verification of properties that hold against particular contracts.Solidity* is designed to be a dialect of Solidity. Contracts inSolidity* are translated into F* which is a ML-based language and allowsto certify properties of programs using automatic and semi-automaticprovers. Other contract programming languages include a domain-specificlanguage (DSL) for defining financial contracts such as FX future, swap,option and other derivative contracts In the DSL, each contract isdefined as a cash flow between parties that depend on stochasticallyfluctuating values, such as FX rates called observables, and can becomposed of simpler contracts. It also has a type system that helpsinfer properties, such as causality of contracts. Although contracts inthis DSL are not designed to run on blockchain platforms, it primarilyaddresses automation of financial transactions.

There exists a trend to regard smart contracts as smart legal contracts.In fact, some strongly advocate, primarily from a legal and accountingperspective, the concept of ‘Ricardian contract’ as a basis of smartcontracts, according to which smart contracts are not just softwareprograms for automatic transaction execution, but instead they shouldrefer to legal contract agreements in a machine-readable format. Towardthis direction, a trace-based contract model that incorporates ‘blameassignment’ may include a DSL based on the model. According to theirformalism, each contract takes a trace (a sequence of events) anddetermines whether no contract breach is detected or a breach is causedby some particular party. They show that this encompasses variousaspects of contracts including obligations, permissions, and reparation.

More recently, an ACCORD project has been launched, which aims toestablish standards for smart legal contracts. The key concept proposedby the project is reusable domain-specific legal contract templates,each of which is defined as a triple of a data model for transactions, adocument in a natural language that includes variables that may beinstantiated to values defined in the data model, a set of codefragments that implement blockchain transactions. Template engines suchas Cicero generate programs executable on either Hyperledger Fabric(HLF) or Ethereum Virtual Machine (EVM).

Next, it is useful to describe how smart contracts work on existingblockchain platforms such as Ethereum and Hyperledger Fabric, anddescribe which parts are addressed by the present application. From ahigh-level perspective, blockchain platforms commonly providefunctionality to access transactional data stored in ledger database(s)which are either globally shared (Bitcoin/Ethereum/HLF) or distributed(Corda), invoke transactions, and add blocks. From the application pointof view, these are regarded as API functions or virtual machineinstructions.

Smart contracts are blockchain applications that are characterized bystrong programmability (Turing completeness) and a high degree ofautonomicity. In addition, it is often the case that smart contracts aredefined without directly employing blockchain functionality, which areinstead encapsulated beyond an abstraction layer. For example, smartcontracts in Solidity look like C++ classes, each of which carriesinstance variables and method functions. These are, when declared in thepublic scope, mapped to state variables (stored in the ‘storage’ ledger)and transactions, respectively. There is no direct way of extendingblocks within a Solidity program. A smart contract in HyplerledgerFabric, which is called chaincode, is a software component with aparticular interface written in Go, Java, or JavaScript. In theinterface, the Invoke function is defined as an entry point oftransactions. It takes a transaction name and an object that hasfunctions to handle a ledger and events.

The present application describes a small LDL_(f)-based domain-specificlanguage (DSL) to define contracts, in terms of requirement enforcementand automatic contract generation. The DSL itself is defined primarilyfor demonstrating the feasibility of the described technologies and thusis intentionally designed to be minimalistic. Primary building blocks ofthe DSL are contracts, each of which is defined as a tuple of protocol,properties, and rules. The first two (i.e. protocol and properties)constitute the high-level specification layer of the contract whereasthe third (i.e. rules) constitutes the rule layer that includesimplementation details. The formal syntax of the DSL is defined below.For examples, refer to the toggle switch contract and Safe RemotePurchase (SRP) contracts.

DSL Syntax (Table I): contract ::= protocol_decl property_decl rule_declprotocol_decl ::= protocol protocol ‘;’ ‘;’ protocol ::= event_name |protocol ‘;’ protocol | protocol ‘+’ protocol | protocol ‘*’ | protocol‘?’ property_decl ::= property (ldl_formula ‘;’ )+ rule_decl ::= rule(rule ‘,’ )+ rule ::= except ? on event_name (‘,’ event_name)* ( whencondition (‘{’ code ‘}’)? )? do action (‘{‘ code ‘}’)? condition ::=ldl_proposition | ‘<’ ldl_path ‘>’ condition action ::= ensureldl_proposition | raise event_name | preserve ‘(’ var_name (‘,’var_name)* ‘)’ | action (‘,’ action)+Note the DSL syntax is defined in the Extended Backus-Naur Form (EBNF);those symbols in italic denote non-terminal symbols whereas those inbold and those quoted denote terminal symbols.

Protocol: Each protocol defines a regular-pattern of events to beprocessed by a contract using sequence (;), choice (+), loop (*), andtest (?) operators. This is analogous to regular expressions defined asregular-patterns of characters.

Properties: Each property is defined as a LDL_(f) formula. It specifiesa temporal constraint that the contract needs to satisfy. Properties caninclude atomic propositions like q₀ and q₁ but cannot include eventnames. This is for separating out the event-processing part of thesemantics ([[.]]_(proto)) (Table III) from the other parts forsimplicity. When more than one property is defined in a contract, theyare meant to be connected conjunctively. The form “[[ ]]” can beregarded as a computer program (or procedure) that takes a contract asinput and derives a single LDL_(f) formula as output. For example, [[c]]denotes an output LDL_(f) formula obtained by passing a contract c, asinput, to the program.

Rules: Each rule is defined in the ECA (event-condition-action) style asa triad of an event, a condition formula, and a sequence of actions. Itspecifies how the contract reacts to a particular event. The conditionpart of a rule is defined as an LDL_(f) formula. Note a temporalcondition, when <ρ>ϕ, examines, upon event arrival, whether thepreceding event trace matches ρ and ϕ holds in the current state. Theaction part is defined as a sequence of two sorts of unit actions,namely (a1) ensure ϕ action that ensures a proposition ϕ turns out tohold when the event processing is complete, and (a2) raise e action thatraises an event e subsequently after processing the event that fires therule. Meanwhile, for convenience, several shorthand expressions areutilized: (1) on e₁, e₂ . . . is a shorthand for on e₁ . . . followed byon e₂ . . . (2) except on e₁, e₂ means “on any event except e₁ and e₂”.(3) do preserve (q, . . . ) means “none of q, . . . changes its value”and is equivalent with when q do ensure q in conjunction with when !q doensure !q. Note !q denotes the negation of q.

Code: The condition and action parts of a rule can carry extra code fordefining implementation details that do not directly appear in thenon-code parts of the rule. Conceptually, each code part and itscorresponding non-code part are respectively considered as a refinementand an abstraction of the other. For concreteness of discussion,JavaScript has been adopted for code definition, although technicallythe code is not restricted to any particular language.

Linear Dynamic Logic on finite traces (LDL_(f)) is an extension ofLinear Temporal Logic on finite traces (LTL). The primary advantage ofLDL_(f) over LTL is that LDL_(f) includes regular paths in formulas forspecifying modality. For instance, [ ]ψ (safety: a proposition ϕ alwaysholds, or !ϕ never happens) and < >ϕ (liveness: ϕ will eventually hold)in LTL are equivalently represented in LDL_(f) as [true*]ϕ (≡!<true*>!ϕ)and <true*>ϕ. Further, LDL_(f) also allows defining formulas like<(light_on; light_off)*> last which has no LTL equivalent but specifiesthat two (exclusive) states, light_on and light_off, alternate with eachother through the end of computation, where last (=[true] false) is aformula that holds only at the end of a trace. Let A={A; . . . } denotea set of atomic propositions. Then, the formal syntax of LDL_(f) and its(trace-based) semantics are defined as shown in Table II, where π=(π(0),. . . , π (last)), ϕ holds at the i^(th) position of π.

The expressiveness of LDL_(f) is strictly higher than LTL and its classas a language is exactly the same as the class of the regular language.As a consequence, instead of introducing regular modeling languages,separately from formula definition languages, such as Promela for theSPIN LTL model checker, LDL_(f) can be directly used for defining models(contracts in our case). This lies as the underlying foundation of thedomain-specific language (DSL).

LDL_(f) Syntax (Table II): Temporal formula φ ::= A | ‘!’ φ | φ₁ ‘&’ φ₂| ‘<’ ρ ‘>’ φ Atomic proposition A ::= propositional variablePropositional formula ψ ::= temporal formula without modality Regularpath ρ ::= ψ | φ ‘?’ ρ₁ ‘+’ ρ₂ | ρ₁ ‘;’ ρ₂ | ρ ‘*’

Note those quoted characters in the above denote terminal symbols.

LDL_(f) Semantics. The semantics of a LDL_(f) formula ϕ is defined withrespect to a finite trace ϕ and a position i at the trace as π, i|=ϕ,which should be interpreted as: given a finite trace π=(740, . . . ,π(last)), ϕ holds at the i-th position of π. Formally, the semantics isdefined as follows:

π,i |= A iff A ∈ π (i) ⊂ A π,i |= !φ iff π,i |= φ does not hold π,i |=φ₁ & φ₂ iff π,i |= φ₁ and π,i |= φ₂ π,i |= <ψ> φ iff i < last and π (i)|= ψ and π,i +1 |= φ π,i |= < φ₁?> φ₂ iff π,i |= φ₁ and π,i |= φ₂ π,i |=<ρ₁ + ρ₂> φ iff π,i |= <ρ₁> φ or π,i |= <ρ₂> φ π,i |= <ρ₁ ; ρ₂> φ iff<ρ₁> <ρ₂>φ π,i |= <ρ*> φ iff π,i |= φ, or i < last and π,i |= <ρ> <ρ*> φ(ρ is not of the form ψ?)

Domain-specific language (DSL) Semantics: Each contract is defined by aprotocol p, a set of properties Φ={ϕ1, ϕ2, . . . }, and a set of rulesR={r₁, r₂; . . . }. For a contract c=(p,Φ,R), the semantics [[c]] aredefined by its shallow-embedding into LDL_(f) as follows:[[c]]=[[p]]_(proto) & Λ_(φ∈Φ)φ& Λ_(r∈R)[[r]]_(rule)

-   -   Note that Λ_(φ∈Φ)φ and Λ_(r∈R) [[r]]rule respectively denote the        logical conjunction of ϕ that ranges over the elements of Φ and        the logical conjunction of [[r]]_(rule) where r ranges over the        elements of R.

Protocol p to [[p]]_(proto): Each event-processing operation is mappedto a single-step transition between π(i) and π(i+1) for some i, that is,processing of an event is an atomic operation in the semantics. In thisregard, the following LDL_(f) formulas are defined for representing howevents are being processed at the current position of a trace:

-   -   idle is a proposition indicating no event has been processed at        the current position of a trace.    -   done(e) indicates that an event e has just been processed        through the transition between the preceding position and the        current position. It turns out “idle” is equivalent with        !done(e) for any e. Employing these formulas, each protocol p        may be mapped to a corresponding LDL_(f) path [[p]]_(proto) as:        [[p]]_(proto)=<idle; proto2ldl(p)>(last & idle)    -   where the auxiliary proto2ldl function is defined as shown in        Table III.

Properties Φ to Λ_(φ∈Φ)Φ: Φ={ϕ₁, ϕ₂ . . . } is straightforwardly mappedto the conjunction of the formulas in Φ.

Rules R to Λ_(r∈R)[[r]]_(rule): Each rule r in R is defined as a safetyproperty (of the form [true*]ϕ as shown in Table III), where act(a) mapsan action a to a LDL_(f) formula as follows:

act (raise e)=<true> done (e)

act (ensure ψ)=ψ

For example, on toggle when_off do ensure_on is translated to:

-   -   [true*] (<_off> done (toggle)-> <_off> (done (toggle) & _on))

[[⋅]]_(proto) and [[⋅]]_(rule) are defined as follows:

[[p]]_(proto) = <idle ; proto2ld l(p)> (last & idle) where proto2ldl(p): protocol => LDL_(f) path is defined as: proto2ldl(e) = done(e)proto2ldl(p; p’) = proto2ldl(p); proto2ldl(p’) proto2ldl(p + p’) =proto2ldl(p) + proto2ldl(p’) proto2ldl(p*) = (proto2ldl(p)) *proto2ldl(p?) = (proto2ldl(p))? [[on e when ψ do a₁, a₂,...]]_(rule) =[true*] (<ψ> done(e) −> <ψ> (done (e) & Λ_(i) act(a_(i))) [[on e when<ρ> ψ do a₁, a₂,...]]_(rule) = [true*] (<ρ; ψ> done(e) −> < ρ; ψ> (done(e) & Λ_(i) act(a_(i))) Table III [[.]]_(proto) : protocol to LDL_(f)formula AND [[.]]_(rule) : rule to LDL_(f) formula

Smart contracts 108 may be verified in a formal and static manner bymeans of converting them to LDL_(f) formulas using [[.]] and running adecision procedure for solving LDL_(f) satisfiability. For example,given a contract c, we can verify whether:

-   -   1) c accepts input events in a particular protocol p,    -   2) c has a particular property ϕ, and    -   3) c is a ‘refinement’ (or ‘specialization’) of another contract        c′.

Formal verification of these are equivalently reduced to the followingLDL_(f) verification:

-   -   1) Acceptance of a protocol p by c: [[p]]_(proto)|[[c]]    -   2) Model checking of a property ϕ over c: [[c]]|=ϕ    -   3) Contract refinement from c to c′: [[c′]]|=[[c]]

Requirements can be formally enforced on contracts and the mechanism canbe exploited for automatic contract generation. Each contract is definedas a tuple, or ordered list, of protocol, formulas, and rules. Byseparating out the first two of them, the following domains forcontracts are defined as:

contract=specification×rules

specification=protocol×properties

requirement=specification

rule=event×condition×action

Note that for each of protocol, property, and rule, its default valuemay be defined, namely any*, true, and on any when true do ensure true,which work as identity elements for conjunction. To create a contractfrom a collection of rules, we first select particular rules, using somepredicate, and fill in the default protocol and property values topromote it to a contract.

select: (rule→bool)→rules→contract

By passing a filter predicate f, select (f,R) yields (any*; {true},{r∈R|f(r)}). For instance, f(e; c; a)=true (if e=e₁) or false(otherwise) is a filter for selecting the rules for the e₁ event.

Given a requirement (p₁,Φ₁) and a contract c=(p₂,Φ₂,R₂), we defineenforcement of the requirement on c as another contract that is avariant of c with (p₁,Φ₁) enforced upon. Formally, the enforce functionis typed as:

enforce:requirement→contract→contract

and enforce((p₁,Φ₁), (p₂,Φ₂,R₂)) returns (p₁∩p₂, Φ₁∪Φ₂, R₂)

Note that p₁ intersection with p₂ is the intersection of protocols p₁and p₂, while Φ₁ union with Φ₂ and R₁ union with R₂ denote conjunctiveunions of formulas and rules, respectively. As a direct consequence ofthe definition, he following equation can be guaranteed to hold:

[[enforce((p₁,Φ₁), c)]]=[[p₁]]_(proto) & Λ_(φ∈Φ1)φ& [[c]]

Note also, as a natural consequence, this implies that the requirement(p₁,Φ₁) is enforced on c′=enforce((p₁,Φ₁), c)]] in the sense of[[c′]]=[[p₁]]_(proto) & & Λ_(φ∈Φ1)φ.

Next, a systematic means to compose contracts is provided. In so doing,assume that each contract (p,Φ,R) is of the form (p, {<ρ> last},R)(i.e., Φ={<ρ>(last}). Note that each LDL_(f) formula can be equivalentlyrepresented as <ρ> last for some ρ. Considering this and the fact thatΦ={ϕ₁, ϕ₂; . . . } actually denotes Λ_(φ∈Φ)φ, we can safely assume thiswithout sacrificing generality.

a) Sequence c₁; c₂

Given c₁=(p₁, {<ρ₁> last}; R₁) and c₂=(p₂, {<ρ₂> last},R₂),

c₁; c₂ is composed by sequentially combining c₁ and c₂:c ₁ ;c ₂=(p ₁ ;p ₂;{<ρ₁θ₁;ρ₂θ₂> last},R ₁ ∪R ₂), where:

-   -   θ_(i)={(ψ & g_(i))/ψ|ψ is a proposition in ρ_(i)}    -   R_(i)′={(e, c & g_(i), a)|(e,c,a)∈R_(i)}        Note that m_(i) denotes a substitution: ρ_(i)θ_(i) yields a        regular path obtained by substituting each proposition that        appears in p_(i) with ψ & g_(i). Note also that g₁ and g₂ are        guard formulas added to the path/rule parts of c₁; c₂ for        distinguishing whether each of them originates from c₁ or c₂.        For instance, by introducing fresh new atomic propositions A₁        and A₂, g₁ and g₂ can be defined as A₁ & !A₂ and !A₁ & A₂,        respectively.

b) Choice c₁+c₂

-   -   Given c₁ and c₂ in the same way, c₁+c₂ is composed by        disjunctively connecting c₁ and c₂:        c ₁ +c ₂=(p ₁ +p ₂,{<ρ₁θ₁+ρ₂θ₂> last},R ₁ ′∪R ₂′)

c) Loop c*

-   -   Given c=(p, {<ρ> last}, R), c* is composed by making a loop for        repeating c for 0 or more times:        c*=(p*,{<ρ*> last},R)

Toggle Switch Example: A part of an example toggle switch contract iscomposed of two building-block contracts, which we here call c_(on) andc_(off), as (c_(on); c_(off))*. The only difference from the versiondescribed previously, which is obtained as a result of automaticcontract generation, is that no property definition is included. Theswitch-alternation property is added to (c_(on); c_(off))* by applyingenforce to the switch specification.

SRP Seller and Buyer Example: The contract includes the following twosub-contracts: A Seller c_(S): which receives a single ‘purchase’ eventcarries an atomic proposition denoted by _q0 that is set to falseinitially, and rules for ‘purchase’. A Buyer c_(B): which receives thesubsequent events after ‘purchase’, carries q1, q2, and all theremaining rules. Therefore, c_(S); c_(B) defines a contract. Thedifferences are the temporal property that is missing in c_(S); c_(B)and auxiliary propositions such as A₁ and A₂ that appear in c_(S); c_(B)but have no effect in this case. The original version provides an extra“abort” feature that is defined as follows:

event Aborted( ); function abort( ) public onlySellerinState(State.Created) { emit Aborted( ); state = State.Inactive;seller.transfer(this.balance); }

In order to incorporate this into the contract, the Abort contract isdefined, denoted by c_(abort):

protocol abort ;; property !_q3; // _q3 indicates ’inactive’ rule onabort when !_q3 {_event.data.sender == _data.seller } do raise aborted,ensure _q3 // inactive { transfer(_data.seller, _data.balance); };except on abort do preserve (_q3);

Then, c_(S); (c_(B)+c_(abort)) incorporates the feature.

Expressed in Solidity, the Safe Remote Purchase contract, without the“abort” feature, may be represented as shown below:

contract Purchase { uint public value; address public seller; addresspublic buyer; enum State { Created, Locked, Inactive } State publicstate; function Purchase( ) public payable { seller = msg.sender; value= msg.value / 2; require((2 * value) == msg.value); } modifiercondition(bool _condition) { require(_condition); _; } modifieronlyBuyer( ) { require(msg.sender == buyer); _; } modifier onlySeller( ){ require(msg.sender == seller); _; } modifier inState(State _state) {require(state == _state); _; } event PurchaseConfirmed( ); eventItemReceived( ); function confirmPurchase( ) publicinState(State.Created) condition(msg.value == (2 * value)) payable {emit PurchaseConfirmed( ); buyer = msg.sender; state = State.Locked; }function confirmReceived( ) public onlyBuyer inState(State.Locked) {emit ItemReceived( ); state = State.Inactive; buyer.transfer(value);seller.transfer(this.balance); } }

Expressed in domain-specific language (DSL), the Safe Remote Purchasecontract, without the “abort” feature, may be represented as shownbelow:

protocol purchase; confirmPurchase; purchaseConfirmed; confirmReceived;itemReceived ;; property !_q0; // for seller. _q0 indicates its state is’created’ [true*] (!_q0 => !_q1 & !_q2); rule on purchase // seller when!_q0 { _event.data.value % 2 = 0 } do ensure _q0 // created { pay(_event); _data.seller = _event.data.sender; _data.value =_event.data.value / 2; }; on confirmPurchase // buyer when !_q1 & !_q2 {_event.data.value == (2 * _data.value) } do raise purchaseConfirmed,ensure _q1 & !_q2 // locked { pay (_event); _data.buyer =_event.data.sender; }; on confirmReceived // buyer when _q1 & !_q2 //locked { _event.data.sender == _data.buyer } do raise itemReceived,ensure !_q1 & _q2 // inactive { transfer (_data.buyer, _data.value);transfer (_data.seller, _data.balance); }; except on purchase dopreserve (_q0); except on confirmPurchase, confirmReceived do preserve(_q1, _q2);|

Based on the compositional contract construction now established, acontract may be semi-automatically generated contract(s) that meet aparticular requirement, in which the non-automatic portion is aninstantiation of guard formulas that appear as free variables in thecomposition operations. Specifically, given a set of contracts C₀ and arequirement (p,Φ), the following two-step procedure may be utilized tocombine contracts in C₀ and generate another set of contracts C₂ each ofwhich meets the requirement.

-   -   1) Construct, by combining contracts in C₀, a set of ‘candidate’        contracts C₁, each element of which carries a protocol p′ that        is equal with (or larger than) p. Note this involves a recursive        operation described below:        c=(p′,Φ′,R′)∈C ₁        -   ⇔c is composed of c₁; c₂, . . . for some c_(i)∈C₀            [[p]]_(proto)|=[[p′]]_(proto)    -   2) Enforce the requirement on the contracts in C₁ and filter out        those that derive unsatisfiable LDL_(f) formulas.        C ₂ ={c′|c∈C ₁ ,c′=enforce((p,Φ),c),∃π,0|=[[c′]]}

The key step is the construction of C₁, which is described in detail asfollows: First, a set of sets of protocols P are constructed byrecursively decomposing p in the following manner:

-   -   1) Initially, P is set to {{p}}    -   2) For each element P={p1; p2; . . . } of P, if p_(i) for some i        is either of the form ‘q₁; q₂’, ‘q₁+q₂’, or ‘q*’, add to P a new        set of protocols P′ obtained by replacing p₁ in P with ‘q₁, q₂’,        ‘q₁, q₂’, or ‘q’, respectively.    -   3) Terminate when there remains no room for P to expand.

Intuitively, each element P of P denotes a set of protocols from whichwe can compose p by using the 3 composition operators. Then, selectthose elements of P that are included in the protocols of C₀ ({P∈P|P⊂{p(p,Φ,R)∈C₀}}). Note that each of those elements naturally indicates howto combine contracts in C₀, that is, if p and p′ in P derive from p; p′at the second step of the above recursive procedure, this indicates thecorresponding contracts c and c′ should be combined as c; c′. Takingthis into account, we finally construct C₁ by combining contracts in C₀exactly in the indicated manner.

For the toggle switch example, C₀ is initially set to {c_(on); c_(off)},from which C₁={(c_(on); c_(on))*; (c_(on); c_(off))*, . . . , (c_(off);c_(off))*} is constructed. Then, by enforcing the requirement (p;Φ) andfiltering out those derive unsatisfiable models, C₂={enforce((p,Φ),(c_(on); c_(off))*)} is obtained as the result, where p and 0 denote theprotocol and the properties of the specification of the target contract,respectively. In the same way, the contract can be generated by callingthe algorithm with C₀={c_(S), c_(B)} and a specification.

A set of tools are described herein for running contracts in adomain-specific language (DSL) on Hyperledger Fabric: First, a contractdefinition in the DSL is translated to a semantically-equivalent UMLstatechart in a standardized SCXML format. Then, it is serialized intoJSON and interpreted by the SCXML engine that runs within a chaincodeprocess on HLF. In this section, the tool implementation is described,along with how the tools work. Additionally, some results of evaluationare also described.

1) Contract to DFA: A contract is first translated into a LDL_(f)formula, using [[.]] defined previously. It is translated to adeterministic finite automaton (DFA) that exactly accepts the traces forwhich the formula holds.

2) DFA to Statechart in SCXML: The generated DFA is then furthertranslated into a UML Statechart by directly mapping its states andtransitions to those for a (single flat) statechart. Meanwhile, theevent names and code fragments that appear in the contract definitionare kept separately and restored in the statechart generation. Note thatevent names are all translated to propositions by [[.]] and thus DFAdoes not retain the event names, whereas code fragments included inrules are all discarded by [[.]]. The tool for statechart generationattempts to find, for each state transition, which rule in the sourcecontract corresponds with it. Specifically, this is done by running aLDL_(f) model checker for each transition (q, e, q′) and examining ifthere exists a rule (e, c, a) such that c and a hold at q and q′,respectively. Once corresponding rule(s) are detected, the event namesand the code fragments in the rules are attached to the transition.

The SCXML engine supports many important elements of SCXML includingparallel and hierarchal states, event transmission, and data model andJavaScript execution. It is written in the “Go” language, and isdesigned to be used inside a chaincode, a smart contract of HyperledgerFabric. Transactions to the chaincode are mapped to events of SCXML andrecorded to a shared ledger. Since the chaincode cannot have persistentdata, the states and the values of the data are managed by the SCXMLengine and automatically stored into a Key-Value Store (KVS) whichrepresents the current state of the blockchain system. This update onthe KVS is recorded to the shared ledger. JavaScript programs areexecuted as actions or conditions using the Otto package(https://github.com/robertkrimen/otto) which is a JavaScript interpreterwritten in the Go language. Data of the statechart is handled using theJavaScript programs. In addition, a custom built-in JavaScript functionenables accessing the KVS and sending custom events through thechaincode APIs (PutState, GetState and SetEvent) provided by HyperledgerFabric where the custom events are user-defined events to be sent to aclient program from a chaincode. Interactions for the confirmPurchaseevent are as follows:

-   -   1) A client requests a peer to process a transaction to send the        event confirmPurchase with JSON data        {“value”:10,“sender”:“buyer”} to the statechart.    -   2) The peer calls the Invoke function of Chaincode, which        receives the event name and the JSON data, to handle the        transaction.    -   3) Chaincode sends the event with the JSON data to the SCXML        engine.    -   4) After the SCXML engine receives the event, it retrieves the        current state of the statechart and data stored in the KVS        through chaincode APIs where, for example, the value associated        with the key “value” in the KVS is assigned to the JavaScript        variable _data.value.    -   5) The SCXML engine evaluates guard conditions to determine a        transaction to fire where the value of “value” and “buyer” of        the event data are assigned to the JavaScript variables        _event.value and _event.buyer, respectively.    -   6) The SCXML engine executes an action. During this execution,        the SCXML engine set the custom event purchaseConfirmed to be        sent to the client through a chaincode API.    -   7) Update the current state.    -   8) The updated current state and the data are stored into the        KVS.    -   9) The peer records the transaction to the shared ledger if it        succeeds.    -   10) The custom event is sent to the client.

The performance of the SCXML engine has been evaluated by deploying thechaincode of the SRP example to Hyperledger Fabric running in the “dev”mode and collecting runtime profiling data using pprof. The “dev” modeis an execution mode of Hyperledger Fabric used during a developmentphase, where chaincode may be executed manually in a terminal window. Inthis experiment, a client first initialized the SCXML instance and sentthe confirmPurchase event and the confirmReceived event while retrievingthe current state and the data after each transaction. This scenario wasrepeated 20 times and cumulative times spent by the Invokefunction andits callee functions were collected. Two types of performance overheadthat could not occur in commonly used chaincodes: (1) serialization anddeserialization of states and data of SCXML for storing them in KVS and(2) preparation for the JavaScript execution, the greater part of whichis consumed by the initialization of JavaScript interpreter and the dataserialization for the communication between Go and JavaScript. Theperformance overhead may be reduced by developing a more efficientrepresentation of states and data of SCXML and by writing actions andconditions in Go instead of JavaScript.

FIG. 1A illustrates a network diagram 100 of a blockchain systemincluding a database and smart contracts, according to exampleembodiments. Referring to FIG. 1A, the network 100 includes a blockchainnetwork 112, which may either be a public blockchain network 112 or apermissioned blockchain network 112. Blockchain network 112 includes acollections of nodes or peers 104, which operate together to create andprocess blockchain transactions 116. FIG. 1A illustrates three nodes orpeers 104, identified as node or peer 104A and 104B through 104N.Although three nodes or peers 104 are shown, any number of nodes orpeers 104 may be present in blockchain network 112.

Associated with nodes or peers 104 are smart contracts 108, identifiedas smart contract 108A associated with node or peer 104A, smart contract108B associated with node or peer 104B, and smart contract 108Nassociated with node or peer 104N. A smart contract 108 is a computerapplication or protocol intended to digitally facilitate, verify, orenforce the negotiation or performance of a contract between two or moreblockchain nodes or peers 104. Smart contracts 108 are expected to workhighly automatically without human intervention as much as possible.However, it may be difficult to ensure that they work as specified dueto their high expressiveness and complexity. Errors associated withsmart contacts 108 could be serious because they often involve financialtransactions. The present application describes various embodimentsproviding automatic generation of smart contracts 108 from a formalspecification. Given one or more formal specifications (or requirements)of a smart contract 108, it is possible to generate a smart contract 108that meets the specification in an automated manner. It is also possibleto formally verify whether a specification holds against a generatedsmart contract 108. The present application further describes methodsfor combining and reusing smart contracts 108 to form new smartcontracts 108, as well.

Smart contracts 108 of the present application are created on computingsystems 190 known in the art. In one embodiment, computing systems 190are part of blockchain network 112. In another embodiment, computingsystem 190 is outside the blockchain network 112. In yet anotherembodiment, computing system 190 is a node or peer 104 within theblockchain network 112.

Smart contracts 108 are, in essence, autonomous computer programs whoseoperations are mapped to blockchain transactions. In recent years, newprogramming languages have been created to build executable smartcontracts 108, such as Solidity, Kotlin (API for Corda), and Script.Unfortunately, although smart contracts 108 in these languages work in ahighly autonomous manner without human intervention, they are oftenerror-prone. That is, they may be very difficult to ensure that theywork as intended due to their high expressiveness and complexity.Consequences of unexpected errors could be serious because they ofteninvolve financial transactions. The present application provides variousformal or automatic means for enforcing requirements on smart contracts108: Given a smart contract c 108 and its requirements, commonly definedusing formal logic, it should be possible to automatically generateanother smart contract c′ 108 that is similar to c but is morerestricted so that it meets the requirements.

Further, based on this technology, automatic generation of smartcontracts 108 from formal specification of their requirements isdescribed. Thus, by combining these, the entire process of contractgeneration will be based on solid formal grounds: Starting from a formalspecification of a contract, an executable contract is automaticallygenerated, on which extra requirements can be further enforcedarbitrarily. The primary challenge in attaining these goals is thatthere exists a tradeoff between the expressiveness of underlyingformalism and the feasibility of automation: If an expressive formallanguage is used for contract definition, it is often the case thatexecutable contract programs cannot be automatically generated. This isbecause automatic requirement enforcement and contract generationinvolves satisfiability solving in underlying formal logic, which couldbe decidable or undecidable, and higher expressiveness leads the logicto turning into being undecidable. Consequently, for automation, theexpressiveness of specifications needs to be restricted substantially.This could end up with severe compromises.

Two-layered composable contracts provide such a solution. First, eachcontract definition is divided into two layers, namely a specificationlayer in a formal language based on a decidable logic called LDL_(f) anda rule layer in both LDL_(f) and a programming language such asJavaScript. The former specifies the transaction protocol and logicalproperties of a smart contract 108 whereas the latter definesimplementation details of the transactions. As a key characteristic, thetwo layers need not be related directly but can be defined separatelyand then combined together. Regardless of how the two layers of acontract are defined, the contract as an executable program always meetswhat are defined in its specification layer as long as the definition isconsistent (as an LDL_(f) formula), that is, invalid combinations leadto logical inconsistency and derive no contract program. Exploiting thischaracteristic, given a contract, separately defined extra requirementsmay be combined or included into the specification layer of the contract(requirement enforcement).

Secondly, composition operations are newly provided for both contractspecifications and full-fledged contracts. If contracts have consistentspecifications, composition of them preserves consistency. In anothersense, contract consistency is closed under composition. Based on this,an algorithm for automatic contract generation is presented: Given acontract specification and a set of contracts as building blocks, a newcontract that conforms to the specification can be composed of thebuilding block contracts by only referring to their specification layers(automatic contract generation). Note that all operations withinspecification layers, including both enforcement and composition, makeno negative impact on the feasibility of automation, which is a keyconcept of the present application.

As an example of automatic contract generation, consider the following‘toggle switch’ contract. Suppose there are small contracts that respondto a single ‘toggle’ event—one turns on a switch and the other turns itoff, and they also change the internal switch state to ‘on’ and ‘off’,respectively. Then, suppose further that a new contract is needed thatresponds to an even number of consecutive toggle events and alternatesthe switch state accordingly. The two contracts and the abovespecification of the target contract are defined in a domain-specificlanguage (DSL) as follows:

[2 building-block contracts] protocol toggle ;; |/ single 'toggle ’transaction event rule on toggle do ensure _on { turn_on ( ); }; // ECArule with JavaScript protocol toggle ;; rule on toggle do ensure _off {turn_off ( ); }; [Specification of the target contract] protocol(toggle; toggle)* ;; // even number of 'toggle’ events property //LDL_(f) formulas <(_off; _on)*> last; // alternation of the ’off’ and’on ’ states [true*] !(_on & _off); // ’on ’ or ’off’ holds exclusively

Assuming these as inputs, the algorithm automatically generates thefollowing contract by combining the building-block contracts, only usingcomposition operators, and enforcing the properties defined in thespecification. Note A1 and A2 are fresh atomic propositions introducedfor keeping consistency:

protocol (toggle; toggle)* ;; property <(!_on & _off & A1 & !A2; !_off &_on & !A1 & A2)*> last; rule on toggle when A1 & !A2 do ensure _on {turn_on ( ); }; on toggle when !A1 & A2 do ensure _off { turn_off ( );};

It is guaranteed that the generated contract is consistent and meets thespecification. The contract is then translated into a single LDL_(f)formula, which, together with the JavaScript code fragments attached tothe rule actions, derives a final contract program that is executable ona blockchain platform. The novelty of the present application includesthe following:

-   -   (1) Contract formulation: Each smart contract is defined as a        tuple of protocol, properties, and rules, the first two of which        constitute the specification layer of the contract whereas the        third constitutes the rule layer. Most notably, these are        formulated in a modular manner based on the        separation-of-concern principle, that is, the protocol        (event-based) and the properties (state-based) of a contract can        be defined separately and so can the two layers. This modularity        leads to providing a simple and clear formal semantics for        contracts based on LDL_(f)    -   (2) Requirement enforcement: As a direct consequence of the        separation, it turns out requirements can be enforced on a        contract straightforwardly by simply adding them to its        specification layer.    -   (3) Composition: A set of contract composition operations are        introduced which preserve contract consistency (closure        property), that is, given consistent contracts c₁ and c₂,        composite contracts such as c₁; c₂ and c₁+c₂ are consistent as        well. This allows one to focus on the specification layers of        contracts upon composition.    -   (4) Automatic contract generation: An algorithm to automatically        generate a contract that meets a particular specification is        produced by combining existing contracts.    -   (5) Domain-Specific Language (DSL): For demonstrating the        effectiveness of this approach, a DSL and a set of tools have        been developed that feature the above functionalities. Contracts        defined in the DSL can be translated into contract programs        (chaincodes) that are executable on Hyperledger Fabric (HLF),        for example.

FIG. 1B illustrates a diagram 120 of components operating with smartcontracts and a database, according to example embodiments. FIG. 1Billustrates components of a new smart contract 108. Referring to FIG.1B, the components include a protocol 122, properties 124, and rules 126(however, rules 126 may be empty). The protocol 122 is a regular patternof events, which is a group of one or more sequences or occurrencesrelated to blockchain transactions 116. Properties 124 include one ormore Linear Dynamic Logic on finite traces (LDL_(f)) formulas. Rules 126include an ordered list, where each entry in the list is an event 128, acondition 130, and a sequence of one or more actions 132. LDL_(f) andpreceding representations such as LTL are described in a paper “The Riseand Fall of LTL” by Moshe Y. Vardi of Rice University(https://www.cs.rice.edu/˜vardi/papers/gandalf11-myv.pdf).

The rules 126 include a list, where each entry in the list is an event128, a condition 130, and a sequence of actions 132. In one embodiment,one or more blockchain nodes or peers 104 combines the protocol 122,properties 124, and rules 126 into an intermediate representation 134 inLinear Dynamic Logic on finite traces (LDL_(f)).

A computing system 190 converts the intermediate representation 134 intoa deterministic finite automaton (DFA) 136. A deterministic finiteautomaton (DFA) 136, also known as a deterministic finite acceptor(DFA), a deterministic finite state machine (DFSM), or a deterministicfinite state automaton (DFSA)—is a finite-state machine that accepts orrejects strings of symbols and only produces a unique computation (orrun) of the automaton for each input string. Deterministic refers to theuniqueness of the computation. A DFA is defined as an abstractmathematical concept, but is often implemented in hardware and softwarefor solving various specific problems. For example, a DFA 136 can modelsoftware that decides whether or not online user input such as emailaddresses are valid. DFAs 136 recognize exactly the set of regularlanguages, which are useful for doing lexical analysis and patternmatching.

The computing system 190 also converts the deterministic finiteautomaton (DFA) 136 into an executable smart contract 138. In oneembodiment, the executable smart contract 138 is in a State ChartExtensible Markup Language (SCXML) format. SCXML is an XML-based markuplanguage that provides a generic state-machine-based executionenvironment based on Harel statecharts. A variant of Harel statechartshas gained widespread usage as part of the Unified Modeling Language(UML) The diagram type allows the modeling of superstates, orthogonalregions, and activities as part of a state. SCXML is able to describecomplex finite state machines. For example, it is possible to describenotations such as sub-states, parallel states, synchronization, orconcurrency in SCXML. Instead of SCXML, one may instead generate aJavaScript-only smart contract program that can be directly executed onthe Hyperledger Platform. Other representations in Solidity, Go, etccould also be supported by slightly modifying the current DFA-to-SCXMLtranslator to DFA-to-JS/Solidity/Go.

FIG. 1C illustrates a diagram 150 of components operating with smartcontracts 108 and a database, according to example embodiments.Referring to FIG. 1C, the components include a set of input smartcontracts 152, each of which includes a contract specification 154 andrules 126. The contract specification 154 for each input smart contract152 includes a protocol 122 and properties 124.

Three composition operations 156 are defined and previouslydescribed—Sequence, Choice, and Loop. A computing system 190 combinesthe input smart contracts 152 using specified composition operations 156to form a composite smart contract 158.

The computing system 190 then converts the composite smart contract 158into a deterministic finite automaton (DFA) 136.

The computing system 190 then converts the deterministic finiteautomaton (DFA) 136 into an executable smart contract 138.

FIG. 1D illustrates a diagram 170 of components operating with smartcontracts and a database, according to example embodiments. Referring toFIG. 1D, the components include a set of contracts C₀ 172, each of whichis a reusable smart contract 174. Four reusable smart contracts 174 areshown, identified as reusable smart contract 174A-174D. Each reusablesmart contract 174 has a reusable event pattern 176, identified asreusable event patterns 176A-176D. The system also includes a targetspecification 178, which includes a protocol (regular event pattern) 122and properties (formulas) 124.

The reusable smart contracts 174 and the target specification 178 arecombined by a computing system 190 to form a set of contracts C₁ 182.The set of contracts C₀ 172 are combined using composition operators 156as described with reference to FIGS. 1C and 5B. For each derivedcontract in the set of contracts C₁ 182, its protocol 122 is equal to orlarger than p. In another sense, a contract c=(p′,Φ′,R′) is an elementof the set of contracts C₁ 182 if and only if the following holds:

c is composed of c₁, c₂, . . . for some c₁ that is an element of the setof contracts C₀ 172

Protocol p′ includes p, that is [[p]]_(proto)|=[[p′]]_(proto)

Given protocol 122 and properties 124 (p,Φ) and the set of contracts C₀172, a set of sets of protocols P is constructed by recursivelydecomposing p in the following manner:

-   -   a. Initially P is set to {{p} }    -   b. For each element P={p₁, p₂, . . . } of P,        -   if p_(i) for some i is either of the form ‘q₁; q₂’, ‘q₁+q₂’,            or ‘q*’,        -   we add to P a new set of protocols P′ that is obtained by            replacing p_(i) in P with ‘q₁, q₂’, ‘q₁, q₂’, or ‘q’,            respectively. (P:=P∪{P′}).        -   This step repeats recursively.    -   c. Terminate when there remains no room for P to expand.

Note that each element of P of P denotes a set of protocols from which pmay be composed by using the three composition operations 156. The way Pis constructed naturally indicates how to compose p from the protocolsin P.

Next, contracts c₁, c₂, . . . , c_(n) are selected from the set ofcontracts C₀ 172, if there exists P={p₁, p₂, . . . , p_(n)} in P suchthat the protocols of the contracts, denoted by q₁, q₂, . . . , q_(n)match with P in the sense that q_(i) is equal to or larger than p_(i)for any i=1, . . . , n. (i.e., [[p_(i)]]_(proto)=[[q_(i)]]_(proto)).

Contracts c₁, c₂, . . . are combined to compose a contract in theexactly same way as combining p₁, p₂, to compose p, and add theresulting composite contract to C₁ (C₁ is initially set to empty). Thesteps in this and the previous paragraph are repeated until thereremains no room for C₁ to grow further.

On each contract in the set of contracts C₁ 182, the targetspecification 178 is enforced. Following successful enforcement, thecomputing system converts the set of contracts C₁ 182 into a set ofcontracts C₂ 184. This step enforces the requirements on the set ofcontracts C₁ 182 and filters out those that derive an unsatisfiableLDL_(f) formula.C ₂ ={c′|c∈C ₁ ,c′=enforce((p,Φ),c),∃π such that π,0|=[[c]]}

From the set of contracts C₂ 184, one contract is selected to be atarget contract 186. The target contract 186 is then converted by thecomputing system 190 into deterministic finite automaton 136, which wasdiscussed previously with respect to FIG. 1A and accompanyingdescription. Once expressed as deterministic finite automaton 136, thecomputing system 190 produces an executable smart contract 138.

FIG. 2 illustrates an example of a transactional flow 200 between nodesof the blockchain in accordance with an example embodiment. Referring toFIG. 2, the transaction flow may include a transaction proposal 291 sentby an application client node 260 to an endorsing peer node 281. Theendorsing peer 281 may verify the client signature and execute achaincode function to initiate the transaction. The output may includethe chaincode results, a set of key/value versions that were read in thechaincode (read set), and the set of keys/values that were written inchaincode (write set). The proposal response 292 is sent back to theclient 260 along with an endorsement signature, if approved. The client260 assembles the endorsements into a transaction payload 293 andbroadcasts it to an ordering service node 284. The ordering service node284 then delivers ordered transactions as blocks to all peers 281-283 ona channel. Before committal to the blockchain, each peer 281-283 mayvalidate the transaction. For example, the peers may check theendorsement policy to ensure that the correct allotment of the specifiedpeers have signed the results and authenticated the signatures againstthe transaction payload 293.

Referring again to FIG. 2, the client node 260 initiates the transaction291 by constructing and sending a request to the peer node 281, which isan endorser. The client 260 may include an application leveraging asupported software development kit (SDK), such as NODE, JAVA, PYTHON,and the like, which utilizes an available API to generate a transactionproposal. The proposal is a request to invoke a chaincode function sothat data can be read and/or written to the ledger (i.e., write new keyvalue pairs for the assets). The SDK may serve as a shim to package thetransaction proposal into a properly architected format (e.g., protocolbuffer over a remote procedure call (RPC)) and take the client'scryptographic credentials to produce a unique signature for thetransaction proposal.

In response, the endorsing peer node 281 may verify (a) that thetransaction proposal is well formed, (b) the transaction has not beensubmitted already in the past (replay-attack protection), (c) thesignature is valid, and (d) that the submitter (client 260, in theexample) is properly authorized to perform the proposed operation onthat channel. The endorsing peer node 281 may take the transactionproposal inputs as arguments to the invoked chaincode function. Thechaincode is then executed against a current state database to producetransaction results including a response value, read set, and write set.However, no updates are made to the ledger at this point. In 292, theset of values, along with the endorsing peer node's 281 signature ispassed back as a proposal response 292 to the SDK of the client 260which parses the payload for the application to consume.

In response, the application of the client 260 inspects/verifies theendorsing peers signatures and compares the proposal responses todetermine if the proposal response is the same. If the chaincode onlyqueried the ledger, the application would inspect the query response andwould typically not submit the transaction to the ordering node service284. If the client application intends to submit the transaction to theordering node service 284 to update the ledger, the applicationdetermines if the specified endorsement policy has been fulfilled beforesubmitting (i.e., did all peer nodes necessary for the transactionendorse the transaction). Here, the client may include only one ofmultiple parties to the transaction. In this case, each client may havetheir own endorsing node, and each endorsing node will need to endorsethe transaction. The architecture is such that even if an applicationselects not to inspect responses or otherwise forwards an unendorsedtransaction, the endorsement policy will still be enforced by peers andupheld at the commit validation phase.

After successful inspection, in step 293 the client 260 assemblesendorsements into a transaction and broadcasts the transaction proposaland response within a transaction message to the ordering node 284. Thetransaction may contain the read/write sets, the endorsing peerssignatures and a channel ID. The ordering node 284 does not need toinspect the entire content of a transaction in order to perform itsoperation, instead the ordering node 284 may simply receive transactionsfrom all channels in the network, order them chronologically by channel,and create blocks of transactions per channel.

The blocks of the transaction are delivered from the ordering node 284to all peer nodes 281-283 on the channel. The transactions 294 withinthe block are validated to ensure any endorsement policy is fulfilledand to ensure that there have been no changes to ledger state for readset variables since the read set was generated by the transactionexecution. Transactions in the block are tagged as being valid orinvalid. Furthermore, in step 295 each peer node 281-283 appends theblock to the channel's chain, and for each valid transaction the writesets are committed to current state database. An event is emitted, tonotify the client application that the transaction (invocation) has beenimmutably appended to the chain, as well as to notify whether thetransaction was validated or invalidated.

FIG. 3 illustrates an example of a permissioned blockchain network 300,which features a distributed, decentralized peer-to-peer architecture,and a certificate authority 318 managing user roles and permissions. Inthis example, the blockchain user 302 may submit a transaction to thepermissioned blockchain network 310. In this example, the transactioncan be a deploy, invoke or query, and may be issued through aclient-side application leveraging an SDK, directly through a REST API,or the like. Trusted business networks may provide access to regulatorsystems 314, such as auditors (the Securities and Exchange Commission ina U.S. equities market, for example). Meanwhile, a blockchain networkoperator system of nodes 308 manage member permissions, such asenrolling the regulator system 310 as an “auditor” and the blockchainuser 302 as a “client.” An auditor could be restricted only to queryingthe ledger whereas a client could be authorized to deploy, invoke, andquery certain types of chaincode.

A blockchain developer system 316 writes chaincode and client-sideapplications. The blockchain developer system 316 can deploy chaincodedirectly to the network through a REST interface. To include credentialsfrom a traditional data source 330 in chaincode, the developer system316 could use an out-of-band connection to access the data. In thisexample, the blockchain user 302 connects to the network through a peernode 312. Before proceeding with any transactions, the peer node 312retrieves the user's enrollment and transaction certificates from thecertificate authority 318. In some cases, blockchain users must possessthese digital certificates in order to transact on the permissionedblockchain network 310. Meanwhile, a user attempting to drive chaincodemay be required to verify their credentials on the traditional datasource 330. To confirm the user's authorization, chaincode can use anout-of-band connection to this data through a traditional processingplatform 320.

FIG. 4 illustrates a flow diagram 400 of an example method of enforcinga smart contract execution hierarchy in a blockchain, according toexample embodiments. The method may include one or more of the followingsteps. In some aspects, all or a portion of the method 400 may beperformed by various parts of the system At block 404, a new smartcontract is received, for example, by a validator node or nodeassociated with blockchain network 112.

At block 408, a node in the blockchain network 112 identifies anypreviously appended smart contracts by examining the blockchain.Previously appended smart contracts may be stored in previouslycommitted blocks of the blockchain.

At block 412, a priority assignment subsystem within the blockchainnetwork 112 determines priority levels for the received smart contractin block 404 and any previously appended smart contracts identified inblock 408. If the new smart contract does not have a priority level, thepriority assignment subsystem assigns a default priority level. In someembodiments, a prioritization and resolution subsystem may compare thepriority level of the new smart contract to the priority level of asmart contract previously appended to the blockchain. The prioritizationand resolution subsystem may determine whether the new smart contracthas a lower priority than the previously appended smart contract.

At block 416, if the prioritization and resolution subsystem determinesthat the new smart contract has a lower priority than the previouslyappended smart contract, the priority examination subsystem may examineand compare the terms of the new smart contract and the previouslyappended smart contract. The priority examination subsystem maydetermine whether any of the terms of the new smart contract overlap orconflict with the terms of the previously appended smart contract. Ifthe terms do not overlap or conflict, the method may proceed to block420. If one or more of the terms do overlap or conflict, theprioritization and resolution subsystem may remove or modify theoverlapping or conflicting terms from the new smart contract. Finally,at block 420, the new smart contract is appended to the blockchain.

FIG. 5A illustrates a flow diagram of an example method of executablesmart contract generation in a blockchain, according to exampleembodiments. Referring to FIG. 5A, the method 500 may include one ormore steps as described herein and with respect to FIG. 1B.

At block 502, the method 500 may include defining inputs for a new smartcontract 138. The inputs may include a regular event pattern (protocol122), one or more formulas that each includes a temporal constraint thesmart contract must satisfy (properties 124), and a list of entries.Each entry of the list includes an event 128, a condition 130, and asequence of one or more actions 132.

At block 504, the method 500 may include converting the inputs into asingle Linear Dynamic Logic formula. In one embodiment, the LinearDynamic Logic formula is a Linear Dynamic Logic on finite traces formula(LDL_(f)). The single LDL_(f) formula is a conjunction (“AND”) of 3LDL_(f) formulas—one for the protocol 122, one for the properties 124,and a third for the rules 126.

The expressiveness of LDL_(f) is strictly higher than LTL and its classas a language is exactly the same as the class of the regular language.“Expressiveness” here means that LDL_(f) formulas can include sequences,choices, and loops of propositions, which its predecessor LTL did notallow.

Each regular pattern of events (which is a protocol 122) is includedwithin a contract definition representing one or more event sequencesthat the contract can process. Each single event corresponds to ablockchain transaction 116 such as “purchase item”, “send invoice”,“ship item”, etc. For example, consider 3 events: “purchase”, “invoice”,and “ship” events. A protocol 122 (regular pattern of events) may bedefined as “purchase; ((invoice; ship)+(ship; invoice))”, which means“the first event (transaction) must always be “purchase”. “Purchase” issubsequently followed by either “invoice; ship” or “ship; invoice”. Inthe former, invoice precedes ship, and in the latter, it's the opposite.Consequently, “purchase; ((invoice; ship)+(ship; invoice))” may include2 event sequences: namely (1) purchase, invoice, ship, and (2) purchase,ship, invoice.

At block 506, the method 500 may include translating the LDL_(f)representation into an executable smart contract 138. An executablesmart contract 138 is able to be directly executed by a blockchain node104 of the blockchain network 112. In the preferred embodiment, theexecutable smart contract 138 is in a State Chart Extensible MarkupLanguage (SCXML) format. In other embodiments, the executable smartcontract 138 is in a wide variety of languages including Solidity andGo. Solidity is a statically-typed programming language designed fordeveloping smart contracts that run on Ethereum Virtual Machine (EVM)platforms. Solidity is compiled to bytecode that is executable on theEVM, and developers are able to write applications that implementself-enforcing business logic embodied in smart contracts, leaving anon-repudiable and authoritative record of transactions. Go (oftenreferred to as Golang) is another programming language that may becombined with Javascript and is designed to be used inside a chaincode(smart contract) of Hyperledger Fabric.

FIG. 5B illustrates a flow diagram of an example method of utilizingcontract composition operators in a blockchain, according to exampleembodiments. Referring to FIG. 5B, the method 520 may include one ormore steps as described herein and with respect to FIG. 1C.

At block 522, one or more input smart contracts 152 are identified. Eachof the input smart contracts 152 include a contract specification 154,which includes a regular event pattern 122 and one or more formulas 124that each include a temporal constraint (i.e. time limitation) thecorresponding input smart contract 152 must satisfy.

At block 524, a set of composition operations 156 applicable to the oneor more input smart contracts 152 and contract specifications 154 areidentified. The composition operations 156 include sequence, choice, andloop operations.

At block 526, the one or more input smart contracts 152 are combined,using the set of composition operations 156. When combining two smartcontracts c1 and c2 using one of the composition operators 156, theirprotocols 122 (event patterns) are combined in the same way, while theirproperties 124 (LDL_(f) formulas) are substituted and merged.

At block 528, a computing system 190 creates the composite smartcontract 158 based on the one or more input smart contracts 152 and setof composition operations 156.

At block 530, the computing system 190 translates the composite smartcontract 158 into a deterministic finite automaton 136 and then anexecutable blockchain smart contract 138.

FIG. 5C illustrates a flow diagram of an example method 540 of automaticsmart contract generation in a blockchain, according to exampleembodiments. Referring to FIG. 5C, the method 540 may include one ormore steps as described herein and with respect to FIG. 1D.

At block 542, a target specification 178 is defined for a new targetsmart contract. The target specification 178 includes a protocol 122 andproperties 124.

At block 544, a plurality of reusable smart contracts 174 are obtained.Each reusable smart contract 174 includes a reusable event pattern 176.

At block 546, the plurality of reusable smart contracts 174 are combinedwith the target specification 178 in order to produce a set of contractsC₁ 182.

At block 548, on each contract in the set of contracts C₁ 182, thetarget specification 178 is enforced, and the set of contracts C₁ 182are transformed into a set of contracts C₂ 184.

At block 550, a target contract 186 is selected from the set ofcontracts C₂ 184.

Finally, at block 552, the target contract 186 is translated into anexecutable smart contract 138. In one embodiment, the target contract186 is first translated into a deterministic finite automaton 136 andthe deterministic finite automaton 136 is then translated into theexecutable smart contract 138.

FIG. 6A illustrates an example system 600 that includes a physicalinfrastructure 610 configured to perform various operations according toexample embodiments. Referring to FIG. 6A, the physical infrastructure610 includes a module 612 and a module 614. The module 614 includes ablockchain 620 and a smart contract 630 (which may reside on theblockchain 620), that may execute any of the operational steps 608 (inmodule 612) included in any of the example embodiments. Thesteps/operations 608 may include one or more of the embodimentsdescribed or depicted and may represent output or written informationthat is written or read from one or more smart contracts 630 and/orblockchains 620. The physical infrastructure 610, the module 612, andthe module 614 may include one or more computers, servers, processors,memories, and/or wireless communication devices. Further, the module 612and the module 614 may be a same module.

FIG. 6B illustrates an example system 640 configured to perform variousoperations according to example embodiments. Referring to FIG. 6B, thesystem 640 includes a module 612 and a module 614. The module 614includes a blockchain 620 and a smart contract 630 (which may reside onthe blockchain 620), that may execute any of the operational steps 608(in module 612) included in any of the example embodiments. Thesteps/operations 608 may include one or more of the embodimentsdescribed or depicted and may represent output or written informationthat is written or read from one or more smart contracts 630 and/orblockchains 620. The physical infrastructure 610, the module 612, andthe module 614 may include one or more computers, servers, processors,memories, and/or wireless communication devices. Further, the module 612and the module 614 may be a same module.

FIG. 6C illustrates an example smart contract configuration amongcontracting parties and a mediating server configured to enforce thesmart contract terms on the blockchain according to example embodiments.Referring to FIG. 6C, the configuration 650 may represent acommunication session, an asset transfer session or a process orprocedure that is driven by a smart contract 630 which explicitlyidentifies one or more user devices 652 and/or 656. The execution,operations and results of the smart contract execution may be managed bya server 654. Content of the smart contract 630 may require digitalsignatures by one or more of the entities 652 and 656 which are partiesto the smart contract transaction. The results of the smart contractexecution may be written to a blockchain 620 as a blockchaintransaction. The smart contract 630 resides on the blockchain 620 whichmay reside on one or more computers, servers, processors, memories,and/or wireless communication devices.

FIG. 6D illustrates a common interface for accessing logic and data of ablockchain, according to example embodiments. Referring to the exampleof FIG. 6D, an application programming interface (API) gateway 662provides a common interface for accessing blockchain logic (e.g., smartcontract 630 or other chaincode) and data (e.g., distributed ledger,etc.) In this example, the API gateway 662 is a common interface forperforming transactions (invoke, queries, etc.) on the blockchain byconnecting one or more entities 652 and 656 to a blockchain peer (i.e.,server 654). Here, the server 654 is a blockchain network peer componentthat holds a copy of the world state and a distributed ledger allowingclients 652 and 656 to query data on the world state as well as submittransactions into the blockchain network where, depending on the smartcontract 630 and endorsement policy, endorsing peers will run the smartcontracts 630.

The above embodiments may be implemented in hardware, in a computerprogram executed by a processor, in firmware, or in a combination of theabove. A computer program may be embodied on a computer readable medium,such as a storage medium. For example, a computer program may reside inrandom access memory (“RAM”), flash memory, read-only memory (“ROM”),erasable programmable read-only memory (“EPROM”), electrically erasableprogrammable read-only memory (“EEPROM”), registers, hard disk, aremovable disk, a compact disk read-only memory (“CD-ROM”), or any otherform of storage medium known in the art.

An exemplary storage medium may be coupled to the processor such thatthe processor may read information from, and write information to, thestorage medium. In the alternative, the storage medium may be integralto the processor. The processor and the storage medium may reside in anapplication specific integrated circuit (“ASIC”). In the alternative,the processor and the storage medium may reside as discrete components.For example, FIG. 7A illustrates an example computer system architecture700, which may represent or be integrated in any of the above-describedcomponents, etc.

FIG. 7A illustrates a process 700 of a new block being added to adistributed ledger 730, according to example embodiments, and FIG. 7Billustrates contents of a block structure 750 for blockchain, accordingto example embodiments. Referring to FIG. 7A, clients (not shown) maysubmit transactions to blockchain nodes 721, 722, and/or 723. Clientsmay be instructions received from any source to enact activity on theblockchain 730. As an example, clients may be applications that act onbehalf of a requester, such as a device, person or entity to proposetransactions for the blockchain. The plurality of blockchain peers(e.g., blockchain nodes 721, 722, and 723) may maintain a state of theblockchain network and a copy of the distributed ledger 730. Differenttypes of blockchain nodes/peers may be present in the blockchain networkincluding endorsing peers which simulate and endorse transactionsproposed by clients and committing peers which verify endorsements,validate transactions, and commit transactions to the distributed ledger730. In this example, the blockchain nodes 721, 722, and 723 may performthe role of endorser node, committer node, or both.

The distributed ledger 730 includes a blockchain 732 which storesimmutable, sequenced records in blocks, and a state database 734(current world state) maintaining a current state of the blockchain 732.One distributed ledger 730 may exist per channel and each peer maintainsits own copy of the distributed ledger 730 for each channel of whichthey are a member. The blockchain 732 is a transaction log, structuredas hash-linked blocks where each block contains a sequence of Ntransactions. Blocks may include various components such as shown inFIG. 7B. The linking of the blocks (shown by arrows in FIG. 7A) may begenerated by adding a hash of a prior block's header within a blockheader of a current block. In this way, all transactions on theblockchain 732 are sequenced and cryptographically linked togetherpreventing tampering with blockchain data without breaking the hashlinks. Furthermore, because of the links, the latest block in theblockchain 732 represents every transaction that has come before it. Theblockchain 732 may be stored on a peer file system (local or attachedstorage), which supports an append-only blockchain workload.

The current state of the blockchain 732 and the distributed ledger 732may be stored in the state database 734. Here, the current state datarepresents the latest values for all keys ever included in the chaintransaction log of the blockchain 732. Chaincode invocations executetransactions against the current state in the state database 734. Tomake these chaincode interactions extremely efficient, the latest valuesof all keys are stored in the state database 734. The state database 734may include an indexed view into the transaction log of the blockchain732, it can therefore be regenerated from the chain at any time. Thestate database 734 may automatically get recovered (or generated ifneeded) upon peer startup, before transactions are accepted.

Endorsing nodes receive transactions from clients and endorse thetransaction based on simulated results. Endorsing nodes hold smartcontracts which simulate the transaction proposals. When an endorsingnode endorses a transaction, the endorsing nodes create a transactionendorsement which is a signed response from the endorsing node to theclient application indicating the endorsement of the simulatedtransaction. The method of endorsing a transaction depends on anendorsement policy which may be specified within chaincode. An exampleof an endorsement policy is “the majority of endorsing peers mustendorse the transaction.” Different channels may have differentendorsement policies. Endorsed transactions are forward by the clientapplication to ordering service 710.

The ordering service 710 accepts endorsed transactions, orders them intoa block, and delivers the blocks to the committing peers. For example,the ordering service 710 may initiate a new block when a threshold oftransactions has been reached, a timer times out, or another condition.In the example of FIG. 7A, blockchain node 722 is a committing peer thathas received a new data block 750 for storage on blockchain 730.

The ordering service 710 may be made up of a cluster of orderers. Theordering service 710 does not process transactions, smart contracts, ormaintain the shared ledger. Rather, the ordering service 710 may acceptthe endorsed transactions and specifies the order in which thosetransactions are committed to the distributed ledger 730. Thearchitecture of the blockchain network may be designed such that thespecific implementation of ‘ordering’ (e.g., Solo, Kafka, BFT, etc.)becomes a pluggable component.

Transactions are written to the distributed ledger 730 in a consistentorder. The order of transactions is established to ensure that theupdates to the state database 734 are valid when they are committed tothe network. Unlike a cryptocurrency blockchain system (e.g., Bitcoin,etc.) where ordering occurs through the solving of a cryptographicpuzzle, or mining, in this example the parties of the distributed ledger730 may choose the ordering mechanism that best suits that network.

When the ordering service 710 initializes a new block 750, the new block750 may be broadcast to committing peers (e.g., blockchain nodes 721,722, and 723). In response, each committing peer validates thetransaction within the new block 750 by checking to make sure that theread set and the write set still match the current world state in thestate database 734. Specifically, the committing peer can determinewhether the read data that existed when the endorsers simulated thetransaction is identical to the current world state in the statedatabase 734. When the committing peer validates the transaction, thetransaction is written to the blockchain 732 on the distributed ledger730, and the state database 734 is updated with the write data from theread-write set. If a transaction fails, that is, if the committing peerfinds that the read-write set does not match the current world state inthe state database 734, the transaction ordered into a block will stillbe included in that block, but it will be marked as invalid, and thestate database 734 will not be updated.

Referring to FIG. 7B, a block 750 (also referred to as a data block)that is stored on the blockchain 732 of the distributed ledger 730 mayinclude multiple data segments such as a block header 760, block data770, and block metadata 780. It should be appreciated that the variousdepicted blocks and their contents, such as block 750 and its contentsshown in FIG. 7B are merely for purposes of example and are not meant tolimit the scope of the example embodiments. In some cases, both theblock header 760 and the block metadata 780 may be smaller than theblock data 770 which stores transaction data, however this is not arequirement. The block 750 may store transactional information of Ntransactions (e.g., 100, 500, 1000, 2000, 3000, etc.) within the blockdata 770. The block 750 may also include a link to a previous block(e.g., on the blockchain 732 in FIG. 7A) within the block header 760. Inparticular, the block header 760 may include a hash of a previousblock's header. The block header 760 may also include a unique blocknumber, a hash of the block data 770 of the current block 750, and thelike. The block number of the block 750 may be unique and assigned in anincremental/sequential order starting from zero. The first block in theblockchain may be referred to as a genesis block which includesinformation about the blockchain, its members, the data stored therein,etc.

The block data 770 may store transactional information of eachtransaction that is recorded within the block 750. For example, thetransaction data may include one or more of a type of the transaction, aversion, a timestamp, a channel ID of the distributed ledger 730, atransaction ID, an epoch, a payload visibility, a chaincode path (deploytx), a chaincode name, a chaincode version, input (chaincode andfunctions), a client (creator) identify such as a public key andcertificate, a signature of the client, identities of endorsers,endorser signatures, a proposal hash, chaincode events, response status,namespace, a read set (list of key and version read by the transaction,etc.), a write set (list of key and value, etc.), a start key, an endkey, a list of keys, a Merkel tree query summary, event/transition/stateinformation that derive from State Chart Extensible Markup Language(SCXML), and the like. The transaction data may be stored for each ofthe N transactions.

In some embodiments, the block data 770 may also store new data 772which adds additional information to the hash-linked chain of blocks inthe blockchain 732. Accordingly, the data 772 can be stored in animmutable log of blocks on the distributed ledger 730. Some of thebenefits of storing such data 772 are reflected in the variousembodiments disclosed and depicted herein.

The block metadata 780 may store multiple fields of metadata (e.g., as abyte array, etc.). Metadata fields may include signature on blockcreation, a reference to a last configuration block, a transactionfilter identifying valid and invalid transactions within the block, lastoffset persisted of an ordering service that ordered the block, and thelike. The signature, the last configuration block, and the orderermetadata may be added by the ordering service 710. Meanwhile, acommitter of the block (such as blockchain node 722) may addvalidity/invalidity information based on an endorsement policy,verification of read/write sets, and the like. The transaction filtermay include a byte array of a size equal to the number of transactionsin the block data 770 and a validation code identifying whether atransaction was valid/invalid.

FIG. 8 is not intended to suggest any limitation as to the scope of useor functionality of embodiments of the application described herein.Regardless, the computing node 800 is capable of being implementedand/or performing any of the functionality set forth hereinabove.

In computing node 800 there is a computer system/server 802, which isoperational with numerous other general purpose or special purposecomputing system environments or configurations. Examples of well-knowncomputing systems, environments, and/or configurations that may besuitable for use with computer system/server 802 include, but are notlimited to, personal computer systems, server computer systems, thinclients, thick clients, hand-held or laptop devices, multiprocessorsystems, microprocessor-based systems, set top boxes, programmableconsumer electronics, network PCs, minicomputer systems, mainframecomputer systems, and distributed cloud computing environments thatinclude any of the above systems or devices, and the like.

Computer system/server 802 may be described in the general context ofcomputer system-executable instructions, such as program modules, beingexecuted by a computer system. Generally, program modules may includeroutines, programs, objects, components, logic, data structures, and soon that perform particular tasks or implement particular abstract datatypes. Computer system/server 802 may be practiced in distributed cloudcomputing environments where tasks are performed by remote processingdevices that are linked through a communications network. In adistributed cloud computing environment, program modules may be locatedin both local and remote computer system storage media including memorystorage devices.

As shown in FIG. 8, computer system/server 802 in cloud computing node800 is shown in the form of a general-purpose computing device. Thecomponents of computer system/server 802 may include, but are notlimited to, one or more processors or processing units 804, a systemmemory 806, and a bus that couples various system components includingsystem memory 806 to processor 804.

The bus represents one or more of any of several types of busstructures, including a memory bus or memory controller, a peripheralbus, an accelerated graphics port, and a processor or local bus usingany of a variety of bus architectures. By way of example, and notlimitation, such architectures include Industry Standard Architecture(ISA) bus, Micro Channel Architecture (MCA) bus, Enhanced ISA (EISA)bus, Video Electronics Standards Association (VESA) local bus, andPeripheral Component Interconnects (PCI) bus.

Computer system/server 802 typically includes a variety of computersystem readable media. Such media may be any available media that isaccessible by computer system/server 802, and it includes both volatileand non-volatile media, removable and non-removable media. System memory806, in one embodiment, implements the flow diagrams of the otherfigures. The system memory 806 can include computer system readablemedia in the form of volatile memory, such as random-access memory (RAM)810 and/or cache memory 812. Computer system/server 802 may furtherinclude other removable/non-removable, volatile/non-volatile computersystem storage media. By way of example only, storage system 814 can beprovided for reading from and writing to a non-removable, non-volatilemagnetic media (not shown and typically called a “hard drive”). Althoughnot shown, a magnetic disk drive for reading from and writing to aremovable, non-volatile magnetic disk (e.g., a “floppy disk”), and anoptical disk drive for reading from or writing to a removable,non-volatile optical disk such as a CD-ROM, DVD-ROM or other opticalmedia can be provided. In such instances, each can be connected to thebus by one or more data media interfaces. As will be further depictedand described below, memory 806 may include at least one program producthaving a set (e.g., at least one) of program modules that are configuredto carry out the functions of various embodiments of the application.

Program/utility 816, having a set (at least one) of program modules 818,may be stored in memory 806 by way of example, and not limitation, aswell as an operating system, one or more application programs, otherprogram modules, and program data. Each of the operating system, one ormore application programs, other program modules, and program data orsome combination thereof, may include an implementation of a networkingenvironment. Program modules 818 generally carry out the functionsand/or methodologies of various embodiments of the application asdescribed herein.

As will be appreciated by one skilled in the art, aspects of the presentapplication may be embodied as a system, method, or computer programproduct. Accordingly, aspects of the present application may take theform of an entirely hardware embodiment, an entirely software embodiment(including firmware, resident software, micro-code, etc.) or anembodiment combining software and hardware aspects that may allgenerally be referred to herein as a “circuit,” “module” or “system.”Furthermore, aspects of the present application may take the form of acomputer program product embodied in one or more computer readablemedium(s) having computer readable program code embodied thereon.

Computer system/server 802 may also communicate with one or moreexternal devices 820 such as a keyboard, a pointing device, a display822, etc.; one or more devices that enable a user to interact withcomputer system/server 802; and/or any devices (e.g., network card,modem, etc.) that enable computer system/server 802 to communicate withone or more other computing devices. Such communication can occur viaI/O interfaces 824. Still yet, computer system/server 802 cancommunicate with one or more networks such as a local area network(LAN), a general wide area network (WAN), and/or a public network (e.g.,the Internet) via network adapter 826. As depicted, network adapter 826communicates with the other components of computer system/server 802 viaa bus. It should be understood that although not shown, other hardwareand/or software components could be used in conjunction with computersystem/server 802. Examples, include, but are not limited to: microcode,device drivers, redundant processing units, external disk drive arrays,RAID systems, tape drives, and data archival storage systems, etc.

Although an exemplary embodiment of at least one of a system, method,and non-transitory computer readable medium has been illustrated in theaccompanied drawings and described in the foregoing detaileddescription, it will be understood that the application is not limitedto the embodiments disclosed, but is capable of numerous rearrangements,modifications, and substitutions as set forth and defined by thefollowing claims. For example, the capabilities of the system of thevarious figures can be performed by one or more of the modules orcomponents described herein or in a distributed architecture and mayinclude a transmitter, receiver or pair of both. For example, all orpart of the functionality performed by the individual modules, may beperformed by one or more of these modules. Further, the functionalitydescribed herein may be performed at various times and in relation tovarious events, internal or external to the modules or components. Also,the information sent between various modules can be sent between themodules via at least one of: a data network, the Internet, a voicenetwork, an Internet Protocol network, a wireless device, a wired deviceand/or via plurality of protocols. Also, the messages sent or receivedby any of the modules may be sent or received directly and/or via one ormore of the other modules.

One skilled in the art will appreciate that a “system” could be embodiedas a personal computer, a server, a console, a personal digitalassistant (PDA), a cell phone, a tablet computing device, a smartphoneor any other suitable computing device, or combination of devices.Presenting the above-described functions as being performed by a“system” is not intended to limit the scope of the present applicationin any way but is intended to provide one example of many embodiments.Indeed, methods, systems and apparatuses disclosed herein may beimplemented in localized and distributed forms consistent with computingtechnology.

It should be noted that some of the system features described in thisspecification have been presented as modules, in order to moreparticularly emphasize their implementation independence. For example, amodule may be implemented as a hardware circuit comprising custom verylarge-scale integration (VLSI) circuits or gate arrays, off-the-shelfsemiconductors such as logic chips, transistors, or other discretecomponents. A module may also be implemented in programmable hardwaredevices such as field programmable gate arrays, programmable arraylogic, programmable logic devices, graphics processing units, or thelike.

A module may also be at least partially implemented in software forexecution by various types of processors. An identified unit ofexecutable code may, for instance, comprise one or more physical orlogical blocks of computer instructions that may, for instance, beorganized as an object, procedure, or function. Nevertheless, theexecutables of an identified module need not be physically locatedtogether but may comprise disparate instructions stored in differentlocations which, when joined logically together, comprise the module andachieve the stated purpose for the module. Further, modules may bestored on a computer-readable medium, which may be, for instance, a harddisk drive, flash device, random access memory (RAM), tape, or any othersuch medium used to store data.

Indeed, a module of executable code could be a single instruction, ormany instructions, and may even be distributed over several differentcode segments, among different programs, and across several memorydevices. Similarly, operational data may be identified and illustratedherein within modules and may be embodied in any suitable form andorganized within any suitable type of data structure. The operationaldata may be collected as a single data set or may be distributed overdifferent locations including over different storage devices, and mayexist, at least partially, merely as electronic signals on a system ornetwork.

It will be readily understood that the components of the application, asgenerally described and illustrated in the figures herein, may bearranged and designed in a wide variety of different configurations.Thus, the detailed description of the embodiments is not intended tolimit the scope of the application as claimed but is merelyrepresentative of selected embodiments of the application.

One having ordinary skill in the art will readily understand that theabove may be practiced with steps in a different order, and/or withhardware elements in configurations that are different than those whichare disclosed. Therefore, although the application has been describedbased upon these preferred embodiments, it would be apparent to those ofskill in the art that certain modifications, variations, and alternativeconstructions would be apparent.

While preferred embodiments of the present application have beendescribed, it is to be understood that the embodiments described areillustrative only and the scope of the application is to be definedsolely by the appended claims when considered with a full range ofequivalents and modifications (e.g., protocols, hardware devices,software platforms etc.) thereto.

What is claimed is:
 1. A system, comprising: a processor configured to:define a target specification for a blockchain smart contract, thetarget specification comprising an event pattern and a temporalconstraint; obtain a plurality of reusable smart contracts, eachreusable smart contract comprising a reusable event pattern; combine atleast two of the plurality of reusable smart contracts based on theevent pattern included in the target specification to generate acomposite smart contract; and translate the composite smart contractinto a form that is executable on a blockchain; wherein the compositesmart contract is converted into a deterministic finite automaton; andwherein the deterministic finite automaton is converted into the formthat is executable on the blockchain.
 2. The system of claim 1, whereinthe processor is configured to combine the at least two reusable smartcontracts using one or more composition operators.
 3. The system ofclaim 1, wherein the event pattern and the reusable event patterns eachcomprises a sequence of one or more occurrences related to blockchaintransactions.
 4. The system of claim 1, wherein the form that isexecutable on the blockchain comprises one or more of a unified modelinglanguage or state chart extensible markup language representation. 5.The system of claim 1, wherein the form that is executable on theblockchain comprises one or more contract rules, wherein each of the oneor more contract rules comprises an event, a condition, and a sequenceof one or more actions.
 6. The system of claim 5, wherein a conditionand a sequence of one or more actions define implementation details forcontract rules.
 7. A method, comprising: defining a target specificationfor a blockchain smart contract, the target specification comprising anevent pattern and a temporal constraint; obtaining a plurality ofreusable smart contracts, each comprising a reusable event pattern;combining at least two of the plurality of reusable smart contractsbased on the event pattern included in the target specification togenerate a composite smart contract; translating the composite smartcontract into a form that is executable on a blockchain; wherein thecomposite smart contract is converted into a deterministic finiteautomaton; and wherein the deterministic finite automaton is convertedinto the form that is executable on the blockchain.
 8. The method ofclaim 7, wherein the combining comprises combining the at two reusablesmart contracts using one or more composition operators.
 9. The methodof claim 7, wherein the event pattern and the reusable event patternseach comprise a sequence of one or more occurrences related toblockchain transactions.
 10. The method of claim 7, wherein the formthat is executable on the blockchain comprises one or more of a unifiedmodeling language or state chart extensible markup languagerepresentation.
 11. The method of claim 7, wherein the form that isexecutable on the blockchain comprises one or more contract rules eachcomprising an event, a condition, and a sequence of one or more actions.12. The method of claim 11, wherein a condition and a sequence of one ormore actions define implementation details for contract rules.
 13. Anon-transitory computer readable medium comprising instructions, thatwhen read by a processor, cause the processor to perform: defining atarget specification for a blockchain smart contract, the targetspecification comprising an event pattern and a temporal constraint;obtaining a plurality of reusable smart contracts, each comprising areusable event pattern; combining at least two of the plurality ofreusable smart contracts based on the event pattern included in thetarget specification to generate a composite smart contract; andtranslating the composite smart contract into a form that is executableon a blockchain; wherein the composite smart contract is converted intoa deterministic finite automaton; and wherein the deterministic finiteautomaton is converted into the form that is executable on theblockchain.
 14. The non-transitory computer readable medium of claim 13,wherein the combining comprises combining the at two reusable smartcontracts using one or more composition operators.
 15. Thenon-transitory computer readable medium of claim 13, wherein the eventpattern and the reusable event patterns each comprise a sequence of oneor more occurrences related to blockchain transactions.
 16. Thenon-transitory computer readable medium of claim 13, wherein the formthat is executable on the blockchain comprises one or more of a unifiedmodeling language or state chart extensible markup languagerepresentation.
 17. The non-transitory computer readable medium of claim13, wherein the form that is executable on the blockchain comprises oneor more contract rules each comprising an event, a condition, and asequence of one or more actions.
 18. The non-transitory computerreadable medium of claim 17, wherein a condition and a sequence of oneor more actions define implementation details for contract rules.
 19. Amethod, comprising: defining a target specification for a blockchainsmart contract, the target specification comprising a protocol;obtaining a plurality of reusable smart contracts, each comprising areusable protocol; combining at least two of the plurality of reusablesmart contracts based on the protocol included in the targetspecification to generate a composite smart contract; and translatingthe composite smart contract into a form that is executable on ablockchain; wherein the composite smart contract is converted into adeterministic finite automaton; and wherein the deterministic finiteautomaton is converted into the form that is executable on theblockchain.
 20. The method of claim 19, wherein the combining comprisescombining the at two reusable smart contracts using one or morecomposition operators.
 21. The method of claim 19, wherein the protocoland the reusable protocols each comprise a sequence of one or moreoccurrences related to blockchain transactions.
 22. A non-transitorycomputer readable medium comprising instructions, that when read by aprocessor, cause the processor to perform: defining a targetspecification for a blockchain smart contract, the target specificationcomprising a protocol; obtaining a plurality of reusable smartcontracts, each comprising a reusable protocol; combining at least twoof the plurality of reusable smart contracts based on the protocolincluded in the target specification to generate a composite smartcontract; and translating the composite smart contract into a form thatis executable on a blockchain; wherein the composite smart contract isconverted into a deterministic finite automaton; and wherein thedeterministic finite automaton is converted into the form that isexecutable on the blockchain.